package com.example.cmh.common;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Random;
import java.util.Base64;

public class CaptchaUtil {
    // 生成验证码图片和字符串
    public static Captcha generateCaptcha(int width, int height, int codeCount) {
        String code = randomCode(codeCount);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Arial", Font.BOLD, height - 10));
        g.setColor(Color.BLACK);
        g.drawString(code, 10, height - 10);
        g.dispose();

        // 转为Base64
        String base64Img = null;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "png", baos);
            base64Img = Base64.getEncoder().encodeToString(baos.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Captcha(code, base64Img);
    }

    // 随机生成验证码字符串
    private static String randomCode(int len) {
        String chars = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
        StringBuilder sb = new StringBuilder();
        Random r = new Random();
        for (int i = 0; i < len; i++) {
            sb.append(chars.charAt(r.nextInt(chars.length())));
        }
        return sb.toString();
    }

    // 内部类
    public static class Captcha {
        public String code;
        public String base64Img;
        public Captcha(String code, String base64Img) {
            this.code = code;
            this.base64Img = base64Img;
        }
    }
} 